package com.qiu.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.power.common.util.StringUtil;
import com.qiu.util.general.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/image")
    public void getCaptchaImage(HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        // 生成图形验证码（宽200px，高100px，4位字符）
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 30);
        String key = UUID.randomUUID().toString();
        //把key作为临时令牌发给前端
        redisTemplate.opsForValue().set(key, captcha.getCode(), 3, TimeUnit.MINUTES);
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("verificationKey", key);
        //允许前端访问自定义标头
        response.setHeader("Access-Control-Expose-Headers", "verificationkey");
        // 输出图片流
        captcha.write(response.getOutputStream());
    }

    @PostMapping("/verify")
    public CommonResult verifyCaptcha(@RequestBody Map<String, Object> params) {
        String key = params.get("key").toString();
        String code = params.get("code").toString();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (StringUtil.isNotEmpty(redisCode) && code.equalsIgnoreCase(redisCode)) {
            redisTemplate.delete(key);
            return CommonResult.success("验证成功");
        } else {
            return CommonResult.error("验证失败");
        }
    }
}